package example.documentbased.editorModule.controller
{
	import example.documentbased.editorModule.common.EditorMenuHelper;
	import example.documentbased.editorModule.common.MenuItemTypes;
	import example.documentbased.editorModule.models.EditorModuleModel;
	import example.documentbased.mainModule.models.vo.DocumentVO;
	
	import mx.collections.ArrayList;
	
	import org.etherframework.controller.ReactiveCommand;
	
	import raix.reactive.IObservable;
	import raix.reactive.Observable;
	import raix.reactive.Unit;
	
	public class UpdateEditorMenuCommand extends ReactiveCommand
	{
		private var _editorModel:EditorModuleModel;
		private var _menuHelper:EditorMenuHelper;
		
		public function UpdateEditorMenuCommand(editorModel:EditorModuleModel, 
												menuHelper:EditorMenuHelper)
		{
			_editorModel = editorModel;
			_menuHelper = menuHelper;
			markAsInitialized();
		}
		
		override public function observable():IObservable
		{
			var menuItems:Array = _editorModel.menuItems;
			var enabledTypes:Vector.<uint> = new Vector.<uint>();
			var currentDoc:DocumentVO = _editorModel.currentDocument;
			var openedDocuments:ArrayList = _editorModel.openedDocuments;
			if (!menuItems.length)
			{
				menuItems = _menuHelper.createEditorMenu();
			}
			if (currentDoc && _editorModel.getIsEditedDocument(currentDoc))
			{
				enabledTypes.push(MenuItemTypes.SAVE, MenuItemTypes.SAVE_AS, MenuItemTypes.SAVE_ALL);
			}
			if (openedDocuments && openedDocuments.length)
			{
				enabledTypes.push(MenuItemTypes.CLOSE, MenuItemTypes.CLOSE_ALL);
			}
			if (currentDoc)
			{
				enabledTypes.push(MenuItemTypes.DELETE);
			}
			enabledTypes.push(MenuItemTypes.CREATE, MenuItemTypes.OPEN);
			
			_menuHelper.enable(menuItems[0].children, enabledTypes);
			_editorModel.menuItems = menuItems;
			
			return Observable.value(new Unit());
		}
	}
}